/*
 * Copyright 2010 Electronic Business Systems Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package gr.ebs.gssdroid.activities;

import gr.ebs.gssdroid.R;
import gr.ebs.gssdroid.GssDroid;
import gr.ebs.gssdroid.async.GssAsyncTask;
import gr.ebs.gssdroid.async.GssTasks;
import gr.ebs.gssdroid.async.TaskResult;
import gr.ebs.gssdroid.http.GssHttpCommands;
import gr.ebs.gssdroid.http.SystemErrorException;
import gr.ebs.gssdroid.resource.BackResource;
import gr.ebs.gssdroid.resource.FileResource;
import gr.ebs.gssdroid.resource.FolderResource;
import gr.ebs.gssdroid.resource.OtherUserResource;
import gr.ebs.gssdroid.resource.OthersResource;
import gr.ebs.gssdroid.resource.RestResource;
import gr.ebs.gssdroid.widget.CustomListAdapter;
import gr.ebs.gssdroid.widget.CustomListView;
import gr.ebs.gssdroid.widget.OthersListAdapter;
import gr.ebs.gssdroid.widget.SharedListAdapter;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.webkit.MimeTypeMap;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.AdapterView.AdapterContextMenuInfo;

public class GssOthers extends GssMyFolders{
	OthersResource sharedResource;
	OtherUserResource otherUserResource;
	RestResource currentResource;
	OthersListAdapter adapter;
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		MenuInflater inflater = getMenuInflater();
		final RestResource entry = adapter.getItem(((AdapterContextMenuInfo) menuInfo).position);
		if(entry instanceof FolderResource){
			Log.d("SK"," "+((FolderResource)entry).getParentURI());
		}
		if(entry instanceof FolderResource || entry instanceof FileResource){
			if(entry instanceof FolderResource && ((FolderResource)entry).getParentName()==null){
				return;
			}
			super.onCreateContextMenu(menu, v, menuInfo);
		}
		else
			return;
		
	}
	@Override
	protected void initialize() {
		adapter = new OthersListAdapter((Activity) this, R.layout.row,
				new ArrayList<RestResource>()){
			public void onItemClick(final int position, final View v) {
				RestResource entry = getAdapter().getItem(position);
				RestResource toUse = entry;

				Intent intent = new Intent(getApplication(), GssProperties.class);
				intent.putExtra("resource", toUse);
				startActivityForResult(intent, 2009);

			};
		};
		((CustomListView) findViewById(R.id.fileListView)).setAdapter(adapter);
		if(getDroidApplication().getUserResource()==null||getDroidApplication().getUserResource().getFilesPath()==null){
			handleLogin();
			finish();
			return;
		}
		getTasks().getOthersTask(this).execute(getDroidApplication().getUserResource().getOthersPath());
	}
	
	protected void onEntrySelected(int position, final RestResource resource) {
		if(resource instanceof BackResource){
			BackResource res = (BackResource)resource;
			if(res.getResourceClass().equals(FolderResource.class)){
				getTasks().getFolderTask(this).execute(res.getUri());
			}
			else if(res.getResourceClass().equals(OtherUserResource.class)){
				getTasks().getOtherUserTask(this).execute(res.getUri());
			}
			else if(res.getResourceClass().equals(OthersResource.class)){
				getTasks().getOthersTask(this).execute(getDroidApplication().getUserResource().getOthersPath());
			}
		}
		else if (resource instanceof OtherUserResource) {
			otherUserResource = (OtherUserResource) resource;
			currentResource=otherUserResource;
			getTasks().getOtherUserTask(this).execute(otherUserResource.getUri());
		}
		else if (resource instanceof FolderResource) {
			currentResource=(FolderResource) resource;
			String pathToGet= ((FolderResource) resource).getUri();
			getTasks().getFolderTask(this).execute(pathToGet);
		} else if (resource instanceof FileResource) {
			long filesize = ((FileResource)resource).getContentLength();
			if(filesize>5000000L){
				AlertDialog alertDialogn = new AlertDialog.Builder(this).create();
				alertDialogn.setTitle("Large file size");
				alertDialogn.setMessage("File size is too large are you sure you want to proceed with download?");
				alertDialogn.setButton("Continue",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int which) {
								getTasks().getFileTask(GssOthers.this).execute(((FileResource)resource).getUri());
								dialog.dismiss();
							}
						});
				alertDialogn.setButton2("Cancel",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int which) {
								dialog.dismiss();
							}
						});
				alertDialogn.setCancelable(true);
				alertDialogn.show();
			}
			else{
				getTasks().getFileTask(this).execute(((FileResource)resource).getUri());
			}

		}

	}
	
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		onEntrySelected(arg2, adapter.getItem(arg2));
	}

	protected void populateList(RestResource resource) {
		//currentResource=resource;
		if (resource instanceof OthersResource) {
			sharedResource = (OthersResource) resource;
			List<OtherUserResource> folders = ((OthersResource) resource).getOtherUsers();
			ArrayList<RestResource> data = new ArrayList<RestResource>();
			currentResource=resource;
			data.addAll(folders);
			adapter.setListItems(data);
			adapter.notifyDataSetChanged();
			((TextView) findViewById(R.id.textPath)).setText("Others Shared");
			ImageButton newButton = (ImageButton) findViewById(R.id.newBottomItem);
			newButton.setVisibility(View.INVISIBLE);
		} 
		else if (resource instanceof OtherUserResource) {
			otherUserResource=(OtherUserResource) resource;
			ArrayList<RestResource> data = new ArrayList<RestResource>();
			data.add(new BackResource(getDroidApplication().getUserResource().getOthersPath(), "Others Shared", OthersResource.class, currentResource));
			currentResource=resource;
			data.addAll(((OtherUserResource)resource).getFolders());
			for(FileResource r : ((OtherUserResource) resource).getFiles())
				if(!r.isDeleted())
					data.add(r);
			//data.addAll(((OtherUserResource)resource).getFiles());
			adapter.setListItems(data);
			adapter.notifyDataSetChanged();
			((TextView) findViewById(R.id.textPath)).setText(otherUserResource.getName()+" files");
			ImageButton newButton = (ImageButton) findViewById(R.id.newBottomItem);
			newButton.setVisibility(View.INVISIBLE);
		} 
		else if(resource instanceof FolderResource){
			//boolean isFirstChild = isFolderFirstChildOfShared((FolderResource) resource);
			Log.v("GSSMYFOLDERS","Populate:"+resource.getUri());
			ArrayList<RestResource> data = new ArrayList<RestResource>();
			if(isFolderFirstChildOfShared((FolderResource) resource)){
				data.add(new BackResource(otherUserResource.getUri(), otherUserResource.getName(), OtherUserResource.class, currentResource));
				//adapter.setRootMode(true);
			}
			else{
				data.add(new BackResource(((FolderResource) resource).getParentURI(), ((FolderResource) resource).getName(), FolderResource.class,currentResource));
			}
			currentResource=resource;
			//adapter.setRootMode(false);
			data.addAll(((FolderResource)resource).getFolders());
			data.addAll(((FolderResource)resource).getFiles());
			adapter.setListItems(data);
			adapter.notifyDataSetChanged();
			((TextView) findViewById(R.id.textPath)).setText(((FolderResource)resource).getName()+" files");
			ImageButton newButton = (ImageButton) findViewById(R.id.newBottomItem);
			newButton.setVisibility(View.VISIBLE);
		}
		
	}
	
	private boolean isFolderFirstChildOfShared(FolderResource folder) {
		for (FolderResource r : otherUserResource.getFolders()) {
			String uri = r.getUri();
			if (folder.getUri().equals(uri))
				return true;
		}
		return otherUserResource.getFolders().contains(folder);
	}
	
	
	
	protected CustomListAdapter<RestResource> getAdapter(){
		return adapter;
	}
	
	protected void refresh(){
		if(currentResource instanceof OthersResource)
			getTasks().getOthersTask(this).execute(getDroidApplication().getUserResource().getOthersPath());
		else if (currentResource instanceof OtherUserResource) {
			getTasks().getOtherUserTask(this).execute(currentResource.getUri());
		}
		else if (currentResource instanceof FolderResource) {
			getTasks().getFolderTask(this).execute(currentResource.getUri());
		}
		
	}
	@Override
	public void handleResult(int taskId, TaskResult result) {
		if (result.getException() != null && result.getException() instanceof SystemErrorException) {
			// todo
		}
		switch (taskId) {
		case GssTasks.TASK_GETOTHERS:
			if (result.getResource() != null)
				populateList((OthersResource) result.getResource());
			else if (result.getException() != null)
				handleRestException("TRASH", result.getException());
			break;
		case GssTasks.TASK_GETOTHERUSER:
			if (result.getResource() != null)
				populateList((OtherUserResource) result.getResource());
			else if (result.getException() != null)
				handleRestException("TRASH", result.getException());
			break;
		default:
			super.handleResult(taskId, result);
			break;
		}
	}
	
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		if (getAdapter().getCount() > 0 && getAdapter().getItem(0) instanceof BackResource) {
			BackResource back = (BackResource) getAdapter().getItem(0);
			if(back.getResourceClass()==FolderResource.class)
				getTasks().getFolderTask(GssOthers.this).execute(back.getUri());
			else if(back.getResourceClass()==OtherUserResource.class) {
				getTasks().getOtherUserTask(this).execute(back.getUri());
			}
			else if(back.getResourceClass()==OthersResource.class) {
				getTasks().getOthersTask(this).execute(back.getUri());
			}
		} else {
			super.onBackPressed();
		}
	}
	
	public RestResource getCurrentResource() {
		return currentResource;
	}
}
